package crontab

import (
	"fmt"
	"strconv"
	"time"
    
    "collecter/app/common/helper"
	"github.com/robfig/cron/v3"
)

// init 初始化定时任务

func InitCrontab() {
	fmt.Println(" 定时器服务初始化 ... ")
	enableCrontab := helper.Configer.GetBool("isEnableCrontab")
	if !enableCrontab {
		return
	}
	// 遍历任务配置 && 执行任务
	timeStmt := time.Now()
	crontaber := cron.New(cron.WithSeconds())

	for _, config := range CrontabConfigs {
		if config.RecondLog {
			logMsg := "task " + config.CrontabName + " run at the time: " + timeStmt.Format("2006-01-02-15:04:05")
			helper.Logger.WithField("apart", "crontab").Infoln(logMsg)
		}

		// 执行任务
		if taskId, err := crontaber.AddFunc(config.InterVal, config.Handler); err != nil {
			logMsg := "添加定时任务出错，errmsg：" + err.Error()
			helper.Logger.WithField("apart", "crontab").Errorln(logMsg)
			return
		} else {
			if config.RecondLog {
				logMsg := "task " + config.CrontabName + "[taskId: " + strconv.Itoa(int(taskId)) + "] run finish at " + timeStmt.Format("2006-01-02-15:04:05")
				helper.Logger.WithField("apart", "crontab").Infoln(logMsg)
			}
		}
	}
	crontaber.Start()
}
